<script setup lang="ts">
import { reactive, ref } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { useAuthStore } from '@/store/modules/auth';
import { FormRules } from 'naive-ui';
import { fetchImgCode } from '@/service/api/auth';

defineOptions({
  name: 'PwdLogin'
});
const authStore = useAuthStore();
const { formRef } = useNaiveForm();
const  loginLoading = ref(authStore.loginLoading)
interface FormModel {
  userName: string;
  password: string;
  code: string;
  uuid: string;
	rememberMe:boolean;
}

const model: FormModel = reactive({
  userName: 'admin',
  password: 'admin123',
	code: '',
  uuid: '',
	rememberMe:false,
});
const { formRules } = useFormRules();

const rules: FormRules = {
  password: formRules.pwd,
  code: [{ required: true, message: '请输入验证码', trigger: "blur" }]
};


const imgData = ref('')

// 获取验证码
const loginVerify = () => {
   fetchImgCode().then(res => {
    imgData.value = res.data?.img
    model.uuid = res.data?.uuid
  })
}
loginVerify()

async function handleSubmit(e: MouseEvent) {
  if (!formRef.value) return;
  e.preventDefault();

  formRef.value.validate(async errors => {
    if (!errors) {
      const { userName, password, code, uuid, rememberMe } = model;
      await authStore.login(userName,password,code,uuid,rememberMe);
      if (!loginLoading.value) {
        loginVerify()
        model.code = ''
      }
    }
  });
}
</script>

<template>
  <n-form ref="formRef" :model="model" :rules="rules" size="large" :show-label="false">
    <n-form-item path="userName">
      <n-input v-model:value="model.userName" placeholder="请输入用户名" />
    </n-form-item>
    <n-form-item path="password">
      <n-input v-model:value="model.password" type="password" show-password-on="click" placeholder="请输入密码" />
    </n-form-item>
    <n-form-item path="code">
      <div class="vPicBox">
        <n-input @keyup.enter.native="handleSubmit"  clearable v-model:value="model.code" placeholder="请输入验证码" style="width: 60%" />
        <div class="cursor-pointer">
          <img :src="'data:image/jpeg;base64,'+imgData" alt="请输入验证码" @click="loginVerify()">
        </div>
      </div>
    </n-form-item>
    <n-space :vertical="true" :size="24">
      <div class="flex-y-center justify-between">
        <n-checkbox v-model:checked="model.rememberMe">记住我</n-checkbox>
      </div>
      <n-button
        type="primary"
        size="large"
        :block="true"
        :round="true"
        :loading="loginLoading"
        @click="handleSubmit"
      >
        确定
      </n-button>
    </n-space>
  </n-form>
</template>

<style scoped>
.vPicBox{
	display: flex;
	justify-content: space-between;
}

</style>
